<template>
  <el-card class="admin-user-management">
    <div slot="header">
      <h2>用户管理</h2>
    </div>
    <el-input
      placeholder="输入用户名搜索"
      v-model="searchQuery"
      class="search-input"
      @keyup.enter.native="loadUsers"
    >
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="loadUsers"
      ></el-button>
    </el-input>
    <el-table :data="users" border style="width: 100%; margin-top: 20px">
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="role" label="角色" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'success'">
            {{ scope.row.role === "admin" ? "管理员" : "普通用户" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="注册时间"
        width="200"
      ></el-table-column>
      <el-table-column label="操作" width="300" align="center" fixed="right">
        <template slot-scope="scope">
          <!-- 编辑 -->
          <el-button
            type="text"
            size="small"
            @click="$router.push(`/user/${scope.row.id}/edit`)"
            v-if="isAdminRole && !isAdmin(scope.row)"
            icon="el-icon-edit"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="handleViewUser(scope.row.id)"
            icon="el-icon-view"
          >
            查看
          </el-button>
          <el-button
            type="text"
            size="small"
            danger
            @click="handleDeleteUser(scope.row.id)"
            v-if="isDeleted(scope.row)"
            icon="el-icon-delete"
          >
            删除
          </el-button>
          <el-button
            type="text"
            size="small"
            danger
            @click="resetPassword(scope.row.id)"
            v-if="isDeleted(scope.row)"
            icon="el-icon-refresh-left"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      layout="prev, pager, next"
      :total="total ? total : 0"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    ></el-pagination>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        users: [],
        total: 0,
        pageSize: 5,
        currentPage: 1,
        searchQuery: "",
        preSeachQuery: "",
      };
    },
    computed: {
      isAdminRole() {
        return this.$store.getters.isAdminRole;
      },
      currentUser() {
        return this.$store.getters.user;
      },
    },
    created() {
      this.loadUsers();
    },
    methods: {
      resetPassword(userId) {
        this.$confirm("确定要重置密码吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              await this.$axios.put(`/user/${userId}/reset-password`);
              this.$message.success("密码重置成功");
              this.loadUsers();
            } catch (error) {
              this.$message.error("密码重置失败");
              console.error(error);
            }
          })
          .catch(() => {
            this.$message.info("已取消密码重置");
          });
      },
      isAdmin(row) {
        return row.username === "admin";
      },
      isDeleted(row) {
        return (
          this.isAdminRole &&
          row.username !== "admin" &&
          row.username !== this.currentUser.username
        );
      },
      async loadUsers() {
        try {
          if (this.searchQuery && this.searchQuery !== this.preSeachQuery) {
            this.currentPage = 1;
          }
          let url = `/users?page=${this.currentPage}&pageSize=${this.pageSize}`;
          if (this.searchQuery) {
            url += `&search=${this.searchQuery}`;
          }

          let result = await this.$axios.get(url);
          result = result.data;
          this.users = result.data;
          // console.log("this.users,", this.users);
          this.total = result.total;
        } catch (error) {
          this.$message.error("加载用户列表失败");
          console.error(error);
        }
      },
      handlePageChange(page) {
        this.currentPage = page;
        this.loadUsers();
      },
      handleViewUser(userId) {
        this.$router.push(`/user/${userId}/detail`);
      },
      async handleDeleteUser(userId) {
        this.$confirm("确定要删除这个用户吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              if (userId === this.currentUser.id) {
                this.$message.error("不能删除自己");
                return;
              }
              await this.$axios.delete(`/user/${userId}`);
              this.$message.success("删除成功");
              this.loadUsers();
            } catch (error) {
              this.$message.error("删除失败");
              console.error(error);
            }
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      },
    },
  };
</script>

<style scoped>
  .admin-user-management {
    max-width: 1200px;
    margin: 20px auto;
  }

  .search-input {
    width: 100%;
    margin-bottom: 10px;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
  .dark .el-table__fixed-right {
    background-color: #1d1e1f;
  }
  .dark .el-table__fixed-body-wrapper >>> .el-table__cell .cell {
    background-color: #1d1e1f;
  }
</style>
